//
//  TJAddPayWayController.m
//  Teleport
//
//  Created by xtjun on 2020/6/13.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJAddPayWayController.h"

@interface TJAddPayWayController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
/**图片 */
@property (weak, nonatomic) UIImageView *paymentCodeView;
/**图片链接 */
@property (copy, nonatomic) NSString *imageUrl;
@property (weak, nonatomic) UITextField *accountTextField;
@property (weak, nonatomic) UIButton *saveButton;
@property (weak, nonatomic) UIButton *addButton;
/**1微信 2支付宝 */
@property (assign, nonatomic) NSInteger type;


@end

@implementation TJAddPayWayController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor_Hex(0xf2f2f2);
    
    
    UILabel *nameLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor.blackColor title:@"姓名*".localizedString textAlignment:NSTextAlignmentLeft];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(KNavBarHight);
        make.height.offset(40);
    }];
    
    QMUITextField *nameTextField = [[QMUITextField alloc] init];
    nameTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    //  [nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [nameTextField shearRoundedCornersWithRadiu:3];
    nameTextField.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:nameTextField];
    //    nameTextField.placeholder = @"请输入您的姓名".localizedString;
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.right.offset(-16);
        make.top.equalTo(nameLabel.mas_bottom);
        make.height.offset(40);
    }];
    
    //不可输入
    nameTextField.text = TJUserInfo.readInfo.uname;
    nameTextField.userInteractionEnabled = NO;
    
    UILabel *accountLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor.blackColor title:@"微信账号*".localizedString textAlignment:NSTextAlignmentLeft];
    [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(nameTextField.mas_bottom);
        make.height.offset(40);
    }];
    
    QMUITextField *accountTextField = [[QMUITextField alloc] init];
    [accountTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    accountTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [accountTextField shearRoundedCornersWithRadiu:3];
    accountTextField.backgroundColor = UIColor.whiteColor;
    accountTextField.keyboardType = UIKeyboardTypeASCIICapable;
    [self.view addSubview:accountTextField];
    accountTextField.placeholder = @"请输入微信账号".localizedString;
    [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.right.offset(-16);
        make.top.equalTo(accountLabel.mas_bottom);
        make.height.offset(40);
    }];
    
    
    UILabel *paymentCodeLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor.blackColor title:@"添加收款码*".localizedString textAlignment:NSTextAlignmentLeft];
    [paymentCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(accountTextField.mas_bottom);
        make.height.offset(40);
    }];
    
    UIImageView *paymentCodeView = [[UIImageView alloc] init];
    paymentCodeView.backgroundColor = UIColor.whiteColor;
    paymentCodeView.contentMode = UIViewContentModeScaleAspectFit;
    paymentCodeView.userInteractionEnabled = YES;
    [paymentCodeView shearRoundedCornersWithRadiu:3];
    [self.view addSubview:paymentCodeView];
    [paymentCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(accountTextField);
        make.top.equalTo(paymentCodeLabel.mas_bottom);
        make.height.offset(160);
    }];
    
    
    UIButton *addButton = [UIButton tj_addToView:paymentCodeView];
    [addButton setImage:[UIImage imageNamed:@"pay_add"] forState:UIControlStateNormal];
    [addButton setImage:[UIImage imageNamed:@"pay_add"] forState:UIControlStateHighlighted];
    [addButton addTarget:self action:@selector(didClickAddButton) forControlEvents:UIControlEventTouchUpInside];
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UIButton *saveButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"保存".localizedString];
    saveButton.backgroundColor = UIColor.tj_mainColor;
    [saveButton shearRoundedCornersWithRadiu:22];
    [saveButton addTarget:self action:@selector(didClickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-34);
        make.left.offset(34);
        make.height.offset(44);
        make.centerX.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin - 64);
    }];
    
    if ([_identification isEqualToString:@"weChat"]) {
        accountLabel.text = @"微信账号*".localizedString;
        accountTextField.placeholder = @"请输入微信账号".localizedString;
        self.navigationBar.title = @"添加微信".localizedString;
        _type = 1;
    } else {
        accountLabel.text = @"支付宝账号*".localizedString;
        accountTextField.placeholder = @"请输入支付宝账号".localizedString;
        self.navigationBar.title = @"添加支付宝".localizedString;
        _type = 2;
    }
    accountTextField.font = UIFont_Px(15);
    nameTextField.font = UIFont_Px(15);
    
    
    _paymentCodeView = paymentCodeView;
    _accountTextField = accountTextField;
    _saveButton = saveButton;
    _addButton = addButton;
 
    TJUserInfo *userInfo = TJUserInfo.readInfo;
    
    if (_type == 1) {//微信
        if (userInfo.payWechat.replacingEmptyString.length) {//有值 修改
            
            [self editSetUp];
            //赋值
            self.accountTextField.text = userInfo.wechatName;
            [self.paymentCodeView sd_setImageWithURL:[NSURL URLWithString:userInfo.payWechat]];
            self.imageUrl = userInfo.payWechat;
            
            
        }
    }else{//支付宝
        if (userInfo.payAliay.replacingEmptyString.length) {//有值 修改
             [self editSetUp];
            self.accountTextField.text = userInfo.aliayName;
            [self.paymentCodeView sd_setImageWithURL:[NSURL URLWithString:userInfo.payAliay]];
            self.imageUrl = userInfo.payAliay;
        }
    }
    
    //默认置灰
    [self textFieldDidChange:self.accountTextField];
}

- (void)editSetUp {
    self.saveButton.hidden =  self.addButton.hidden = YES;
    self.navigationBar.rightBarButton = [TJButtonBarButton barButtonWithTitle:@"解绑".localizedString color:UIColor.tj_mainColor target:self action:@selector(didClickNavBarRightButton)];
    
}

- (void)didClickNavBarRightButton{
    
    
    TJUIAlertController *alertController = [TJUIAlertController alertControllerWithTitle:@"提示".localizedString message:@"是否解绑当前收付款方式?".localizedString preferredStyle:QMUIAlertControllerStyleAlert];
    
    
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"确定解绑".localizedString style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        self.saveButton.hidden =  self.addButton.hidden = NO;
        
    }]];
    
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"再想想".localizedString style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }]];
    
    alertController.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:UIColor_Hex(0x9EA0A4),NSFontAttributeName:UIFontMake(16), NSKernAttributeName:@(0)};
    alertController.alertDestructiveButtonAttributes = @{NSForegroundColorAttributeName:UIColorRed,NSFontAttributeName:UIFontMake(16),NSKernAttributeName:@(0)};
    [alertController showWithAnimated:YES];
    
}
/**保存按钮点击 */
- (void)didClickSaveButton {

    NSString *account = self.accountTextField.text;
    [self showloading];
    NSDictionary *parameters = @{@"userId":TJUserInfo.readInfo.userId,
                                 @"url":_imageUrl,
                                 @"name":account,
                                 
    };
    
    NSString *url = @"";
    if (self.type == 1) {//微信
        url = @"member/member/setPayWechat";
    }else{//支付宝
        url = @"member/member/setPayAliay";
    }
    [TJNetworking.shareNetworking POSTNew:url parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSArray *data) {
        
        [self hiddenloading];
        
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}
/**添加按钮点击 */
- (void)didClickAddButton {
    
    TJUIAlertController *alert = [[TJUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"取消".localizedString style:QMUIAlertActionStyleCancel handler:nil]];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"相册".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }]];
    
    [alert addAction:[QMUIAlertAction actionWithTitle:@"拍照".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            
            [self alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromCamera];
        
    }]];
    [alert showWithAnimated:YES];
    
}

#pragma mark - 拍照
- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        TJLog(@"不支持拍照功能");
    }
}


//UIimagePickerCotrollerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *newImage = info[UIImagePickerControllerOriginalImage];
    [self uploadImage:newImage];
    
}
//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

/**输入框监听 */
- (void)textFieldDidChange:(UITextField *)textField {
    _saveButton.userInteractionEnabled =  _accountTextField.text.replacingEmptyString.length && _imageUrl;
    _saveButton.backgroundColor = (_saveButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
}

#pragma mark ——— 图片上传
- (void)uploadImage:(UIImage *)image {
    
    [TJNetworking.shareNetworking updataImageWithImage:image success:^(NSDictionary * resp, id data) {
        
        self.paymentCodeView.image = image;
        self.imageUrl = data;
        [self textFieldDidChange:self.accountTextField];
    } failure:^(NSError *errpr) {
        [TJHud showAutoHideMessage:@"上传失败, 请稍后再试".localizedString];
    }];
}

@end
